package com.wangzh.data.arithmetic.search;

import java.util.Arrays;

public class binary {
    public static void main(String[] args) {
        int[] nums = {1,3,3,3,5,6};

//        System.out.println(leftsearch(nums, 3));
//        System.out.println(rightsearch(nums, 3));
//        Arrays.binarySearch(nums,7);
//        int target = 7;
//        System.out.println(search(nums, target));

        int[] ints = new int[]{leftsearch(nums,3),rightsearch(nums,3)};

        System.out.println(ints);

    }

    //最右边的数值
    public static int rightsearch(int[] nums, int target) {
        int i = 0;
        int j = nums.length-1;

        int temp=-1;

        while(i<=j){
            int middle = (i+j)>>>1;

            if (target<nums[middle]) {
                j=middle-1;
            }else if (target>nums[middle]){
                i=middle+1;
            }else {

                temp=middle;
                //还应该向左边寻找
                i=middle+1;
            }

        }

        return temp;

    }
    //最左边的数值
    public static int leftsearch(int[] nums, int target) {
        int i = 0;
        int j = nums.length-1;

        int temp=-1;

        while(i<=j){
            int middle = (i+j)>>>1;

            if (target<nums[middle]) {
                j=middle-1;
            }else if (target>nums[middle]){
                i=middle+1;
            }else {

                temp=middle;
                //还应该向左边寻找
                j=middle-1;
            }

        }

        return temp;

    }
    public static int search(int[] nums, int target) {
        int i = 0;
        int j = nums.length-1;


        while(i<=j){
            int middle = (i+j)>>>1;

            if (target<nums[middle]) {
                j=middle-1;
            }else if (target>nums[middle]){
                i=middle+1;
            }else {

                return middle;
            }

        }

        return i;

    }
}
